package service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.util.JSON;

import data.Data;


public class Socialgraph {
	public static void Soc(String domain) throws ParseException {
		try {
			URL url = new URL("http://socialgraph.apis.google.com/lookup?q="+domain+"&fme=1&edi=1&edo=1&pretty=1&sgn=1&callback=");
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String content = "";
				char[] buf = new char[102102];
				int numRead=0;
		        while((numRead=reader.read(buf)) != -1){
		            String readData = String.valueOf(buf, 0, numRead);
		            content += readData;
		            buf = new char[102102];
		            System.out.println(readData);
		        }
		        reader.close();
				
				JSONObject json = new JSONObject(content);
				
				JSONObject json2 = (JSONObject) json.get("nodes");
				
				String str = "";
				if(json2.names() != null)
				{
					for (int i = 0; i < json2.names().length(); i++) {
						str = (String) json2.names().get(i);
					}
				}
				JSONObject json1 = (JSONObject) ((JSONObject) ((JSONObject) json.get("nodes")).get(str)).get("nodes_referenced_by");
				
				ArrayList<String> me = new ArrayList<String>(); 
				ArrayList<String> friend = new ArrayList<String>(); 
				if(json1.names() != null)
				{
					for (int i = 0; i < json1.names().length(); i++) {
						String type = (String) ((JSONObject) json1.get((String) json1.names().get(i))).get("types").toString();
						type = type.replaceAll("[\\[\\]\\\"]", "");
			
						if(type.equals("me"))
						{
							me.add(json1.names().get(i).toString());
						}
						if(type.equals("friend"))
						{
							friend.add(json1.names().get(i).toString());
						}
					}
				}
				System.out.println(me.size());
				System.out.println(friend.size());
				DBCollection coll = Data.data("link");
				BasicDBObject basic = new BasicDBObject();
				basic.put("name", domain);
				basic.put("me", me);
				basic.put("friend", friend);
				coll.insert(basic);
			}
		} catch (IOException e) {
			// ...
		}
	}
	public static void main(String[] args) throws ParseException {
		Soc("http://yooarticles.com");
	}
}
